package com.ruike.alisurface.ui.settings;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.usb.UsbDevice;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.NonNull;

import com.lgh.uvccamera.UVCCameraProxy;
import com.lgh.uvccamera.bean.PicturePath;
import com.lgh.uvccamera.callback.ConnectCallback;
import com.lgh.uvccamera.callback.PictureCallback;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.serialport.Ttys3Utils;
import com.ruike.alisurface.utils.BitmipUtil;
import com.ruike.alisurface.utils.OrcIdUtil;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.Base64Util;
import com.voodoo.lib_utils.SharedUtils;
import com.voodoo.lib_utils.imageLoader.GlideImageLoader;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;

/**
 * usb 摄像头 检测页
 */
public class UsbPhoto_Aty extends BaseAty {
    @BindView(R.id.radio_mProductIds)
    RadioGroup radioMProductIdS;
    @BindView(R.id.radio_mProductId1)
    RadioButton radioMProductId1;
    @BindView(R.id.radio_mProductId2)
    RadioButton radioMProductId2;
    @BindView(R.id.img_photo)
    ImageView imgPhoto;
    @BindView(R.id.bt_op0en)
    Button btOp0en;

    @BindView(R.id.bt_take)
    Button btTake;
    @BindView(R.id.baseSetting_goback_imgv)
    ImageView goback;
    @BindView(R.id.tv_layout)
    LinearLayout tv_layout;
    @BindView(R.id.base_video_recording)
    Button baseVideoRecording;

    @BindView(R.id.base_video_start)
    Button baseVideoStart;
    @BindView(R.id.surface_view)
    SurfaceView mSurfaceView;
    @BindView(R.id.timer)
    Chronometer mTimer;
    @BindView(R.id.video_txcvv)
    VideoView videoPlayerTxcvv;

    @BindView(R.id.video_lv)
    LinearLayout video_lv;
    @BindView(R.id.base_open_camera)
    Button baseOpenCamera;


    TextureView textureview;

    @BindView(R.id.bt_idcard)
    Button bt_idcard;
    @BindView(R.id.tv_content)
    TextView tvcontent;


    private SurfaceHolder mSurfaceHolder;
    private boolean isRecording = false;//标记是否已经在录制
    private MediaRecorder mRecorder;//音视频录制类
    private Camera mCamera = null;//相机
    private Camera.Size mSize = null;//相机的尺寸
    private int mCameraFacing = Camera.CameraInfo.CAMERA_FACING_FRONT;// 前置摄像头

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0xAA) {

            } else if (msg.what == 0xAB) {

            } else if (msg.what == 0xAC) {

            } else if (msg.what == 0xBB) {
//                BlApiHttp.setCameraversion(UsbPhotoActivity.this, mProductId);
                imgPhoto.setImageBitmap(null);
                GlideImageLoader.getInstance().loadImage(UsbPhoto_Aty.this, IDpath, imgPhoto, true);
            }
        }
    };


    @Override
    protected int getLayoutResId() {
        return R.layout.app_usb_testphoto;
    }


    @Override
    protected void initViews() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
            }
        }
        initTitleBar(false);
        L.i("tjf-onStart-开灯");
//        initUVCCamera(12342);
        Constant.isShopShipment = true;
        Ttys3Utils.getInstance().ledOpenOrClose(0, 1, true, 15, 15);
        goback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
      /*  try {
            initCamera();
        } catch (Exception e) {
            L.i("initCamera Exception====" + e.toString());
            video_lv.setVisibility(View.INVISIBLE);
            showErrorLongToast(e.getMessage(), 5000);
            e.printStackTrace();
        }*/
        baseOpenCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    initCamera();
                } catch (Exception e) {
                    L.i("initCamera Exception====" + e.toString());
                    video_lv.setVisibility(View.INVISIBLE);
                    showErrorLongToast(e.getMessage(), 5000);
                    e.printStackTrace();
                }
            }
        });

        bt_idcard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(IDpath)) {
                    showErrorLongToast("图片路径为空，请重新拍照", 4000);
                    return;
                }
                showProgressDialog("身份证信息识别中，请等待...", true);
                getORCIdCard(IDpath);
            }
        });
    }

    String IDpath = "";

    @Override
    protected void initData() {
        goback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        String USB_ProductId = SharedUtils.getInstance().getString(ShareKey.USB_ProductId, "12342"); // 启用 支付宝刷脸支付
        if (USB_ProductId.equals("12342")) {
            radioMProductId1.setChecked(true);
        } else {
            radioMProductId2.setChecked(true);
        }
        btOp0en.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mUVCCamera != null) {
                    L.i("tjf-usb-", "==关闭连接 == ");
                    tv_layout.removeAllViews();
                    //                    ImageLoader.clearImage(UsbPhotoActivity.this, imgPhoto);
                    imgPhoto.setImageBitmap(null);
                }
                if (radioMProductId1.isChecked()) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            initUVCCamera(12342);
                        }
                    });
                }
                if (radioMProductId2.isChecked()) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            initUVCCamera(12936);
                        }
                    });
                }

            }
        });

        btTake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (mUVCCamera != null) {
                            mUVCCamera.takePicture("test.jpg");
                        } else {
                            initUVCCamera(12342);
                        }
                    }
                });
            }
        });


        baseVideoRecording.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (baseVideoRecording.getText().equals("开始录视频")) {
                    baseVideoRecording.setText("停止录视频");
                    startRecord();
                } else {
                    baseVideoRecording.setText("开始录视频");
                    stopRecord();
                }
            }
        });

        baseVideoStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (baseVideoStart.getText().equals("播放视频")) {
                    baseVideoStart.setText("停止播放");
                    playVideo();
                } else {
                    baseVideoStart.setText("播放视频");
                    videoPlayerTxcvv.stopPlayback();
                }
            }
        });
    }

    private UVCCameraProxy mUVCCamera;

    /**
     * 初始化UVC摄像头配置及操作
     */

    String mProductId;

    private void initUVCCamera(int ProductId) {
        L.i("tjf-usb-", "开始初始化配置 == " + ProductId);
        mProductId = String.valueOf(ProductId);
        mUVCCamera = new UVCCameraProxy(UsbPhoto_Aty.this);
        // 已有默认配置，不需要可以不设置
        mUVCCamera.getConfig()
                .isDebug(true)
                .setPicturePath(PicturePath.SDCARD)
                .setDirName("/Images/")
                .setProductId(ProductId)
                .setVendorId(3034);//2760

//        mVendorId=3034,mProductId=12342  根据USB摄像头来区分 mVendorId供应商id   mProductId 产品id   ProductId(12936)  日期1020
        textureview = new TextureView(this);
        tv_layout.addView(textureview);
        mUVCCamera.setPreviewTexture(textureview);


        mUVCCamera.setConnectCallback(new ConnectCallback() {
            @Override
            public void onAttached(UsbDevice usbDevice) {
                mUVCCamera.requestPermission(usbDevice);
                L.i("tjf-usb-", "请求连接 ");
            }

            @Override
            public void onGranted(UsbDevice usbDevice, boolean granted) {
                if (granted) {
                    mUVCCamera.connectDevice(usbDevice);
                    L.i("tjf-usb-", "连接 ");
                } else {
                    L.i("tjf-usb-", "请求连接 ");
                    mUVCCamera.requestPermission(usbDevice);
                }
            }

            @Override
            public void onConnected(UsbDevice usbDevice) {
                L.i("tjf-usb-", "打开 ");
                mUVCCamera.openCamera();
            }

            @Override
            public void onCameraOpened() {
                mUVCCamera.setPreviewSize(2592, 1944);
                L.i("tjf-usb-", "打开成功并设置预览及开始");
                mUVCCamera.startPreview();
            }

            @Override
            public void onDetached(UsbDevice usbDevice) {
                L.i("tjf-usb-", "关闭连接");

            }
        });

     /*   mUVCCamera.setPhotographCallback(new PhotographCallback() {
            @Override
            public void onPhotographClick() {
//                mUVCCamera.takePicture();
//                mUVCCamera.takePicture("test.jpg");
            }
        });

        mUVCCamera.setPreviewCallback(new PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] yuv) {

            }
        });*/

        mUVCCamera.setPictureTakenCallback(new PictureCallback() {
            @Override
            public void onPictureTaken(final String path) {
                L.i("tjf-原图地址-" + path);
                cancalimgTimer();
                IDpath = BitmipUtil.cropBitmap(path);
                L.i("tjf-裁剪地址-" + IDpath);
                mHandler.sendEmptyMessage(0xBB);
            }
        });
    }


    Timer imgtime = new Timer();

    public void imgTimer() {
        imgtime.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(0xAC);
            }
        }, 6000);
    }

    public void cancalimgTimer() {
        if (imgtime != null) {
            imgtime.cancel();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        L.i("tjf-onStop-关闭灯");
        tv_layout.removeAllViews();
        Ttys3Utils.getInstance().ledOpenOrClose(0, 1, false, 15, 15);
        Constant.isShopShipment = false;
    }


    /**
     * 初始化相机
     */
    private void initCamera() {
        L.i("初始化相机");
      /*  if (Camera.getNumberOfCameras() == 2) {
            mCamera = Camera.open(mCameraFacing);
        } else {
            mCamera = Camera.open();
        }*/
//        openFrontFacingCameraGingerbread();
        try {
            mCamera = Camera.open();
        } catch (Exception e) {
            e.printStackTrace();
        }
        CameraSizeComparator sizeComparator = new CameraSizeComparator();
        Camera.Parameters parameters = mCamera.getParameters();

        if (mSize == null) {
            List<Camera.Size> vSizeList = parameters.getSupportedPreviewSizes();
            Collections.sort(vSizeList, sizeComparator);

            for (int num = 0; num < vSizeList.size(); num++) {
                Camera.Size size = vSizeList.get(num);

                if (size.width >= 800 && size.height >= 480) {
                    this.mSize = size;
                    break;
                }
            }
            mSize = vSizeList.get(0);

            List<String> focusModesList = parameters.getSupportedFocusModes();

            //增加对聚焦模式的判断
            if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
            } else if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            }
            mCamera.setParameters(parameters);
        }
//        int rotation = getWindowManager().getDefaultDisplay().getRotation();
//        mCamera.setDisplayOrientation(Surface.ROTATION_180);

        mSurfaceView.setZOrderOnTop(true);
        mSurfaceView.setZOrderMediaOverlay(true);
        final SurfaceHolder holder2 = mSurfaceView.getHolder();// 取得holder
        holder2.setFormat(PixelFormat.TRANSPARENT);
        holder2.setFixedSize(640, 480);
        holder2.setKeepScreenOn(true);

        holder2.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
                L.i("mSurfaceView=surfaceCreated");


            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                L.i("mSurfaceView=surfaceChanged");
                video_lv.setVisibility(View.VISIBLE);
                // 将holder，这个holder为开始在onCreate里面取得的holder，将它赋给mSurfaceHolder
                mSurfaceHolder = holder2;
                if (mCamera == null) {
                    return;
                }
                try {
                    //设置显示
                    mCamera.setPreviewDisplay(holder2);
                    mCamera.setDisplayOrientation(180);
                    mCamera.startPreview();
                } catch (Exception e) {
                    e.printStackTrace();
                    releaseCamera();
                    finish();
                }
            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
                L.i("mSurfaceView=surfaceDestroyed");
                // surfaceDestroyed的时候同时对象设置为null
                if (isRecording && mCamera != null) {
                    mCamera.lock();
                }
                mSurfaceView = null;
                mSurfaceHolder = null;
                releaseMediaRecorder();
                releaseCamera();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();

        Constant.isShopShipment = true;
    }

    @Override
    public void onPause() {
        releaseCamera();
        super.onPause();
        Constant.isShopShipment = false;

    }

    /**
     * 停止录制
     */
    private void stopRecord() {
        try {
            //停止录制
            mRecorder.stop();
            mTimer.stop();
            //重置
            mRecorder.reset();
            mCamera.stopPreview();
            ;  //            mStartStop.setImageResource(R.drawable.icon_video_play);
        } catch (Exception e) {
            e.printStackTrace();
        }
        isRecording = false;
    }

    /**
     * 释放MediaRecorder
     */
    private void releaseMediaRecorder() {
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }
    }

    /**
     * 释放相机资源
     */
    private void releaseCamera() {
        try {
            if (mCamera != null) {
                mCamera.stopPreview();
                mCamera.setPreviewCallback(null);
                mCamera.unlock();
                mCamera.release();
            }
        } catch (RuntimeException e) {
        } finally {
            mCamera = null;
        }
    }

    String vedio_path;

    /**
     * 开始录制
     */
    private void startRecord() {
        mTimer.setBase(SystemClock.elapsedRealtime());
        mTimer.setFormat("计时开始 %s");
        mTimer.start();

        if (mRecorder == null) {
            mRecorder = new MediaRecorder(); // 创建MediaRecorder
        }
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.unlock();
            mRecorder.setCamera(mCamera);
        }
        try {
            // 设置音频采集方式
            mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            //设置视频的采集方式
            mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            //设置文件的输出格式
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//aac_adif， aac_adts， output_format_rtp_avp， output_format_mpeg2ts ，webm
            //设置audio的编码格式
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            //设置video的编码格式
            mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
            //设置录制的视频编码比特率
            //mRecorder.setVideoEncodingBitRate(1024 * 1024);
            mRecorder.setVideoSize(1280, 720);
            //设置录制的视频帧率,注意文档的说明:
            mRecorder.setVideoFrameRate(20);

            //设置要捕获的视频的宽度和高度
            // mSurfaceHolder.setFixedSize(320, 240);//最高只能设置640x480
            //mRecorder.setVideoSize(320, 240);//最高只能设置640x480
            //设置记录会话的最大持续时间（毫秒）
            //mRecorder.setMaxDuration(60 * 1000);
            mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
            mRecorder.setOrientationHint(180);
            String path = getExternalCacheDir().getAbsolutePath();
            File dir = new File(path + "/videos");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            vedio_path = dir + "/" + "SmartDoor_video" + System.currentTimeMillis() + ".mp4";

//                mSp.put("video_path",path);
            //设置输出文件的路径
            mRecorder.setOutputFile(vedio_path);
            //准备录制
            mRecorder.prepare();
            //开始录制
            mRecorder.start();
            isRecording = true;
            //btnStartStop.setText("停止");
//                mStartStop.setImageResource(R.drawable.icon_video_stop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private class CameraSizeComparator implements Comparator<Camera.Size> {
        public int compare(Camera.Size lhs, Camera.Size rhs) {
            if (lhs.width == rhs.width) {
                return 0;
            } else if (lhs.width > rhs.width) {
                return 1;
            } else {
                return -1;
            }
        }
    }


    public void playVideo() {
        // 显示视频播放控件
        videoPlayerTxcvv.setVisibility(View.VISIBLE);
        videoPlayerTxcvv.setVideoPath(vedio_path);
        videoPlayerTxcvv.start();
        videoPlayerTxcvv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                videoPlayerTxcvv.setVideoPath(vedio_path);
                videoPlayerTxcvv.start();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTimer.stop();
        releaseCamera();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
//        com.blankj.utilcode.util.FileUtils.deleteAllInDir(Constant.FilePath.IDCARD_PATH);
    }


    private String encodeImage(String path) {
        File imagefile = new File(path);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(imagefile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap bm = BitmapFactory.decodeStream(fis);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        String encImage = Base64Util.encode(b);
        //Base64.de
        return encImage;

    }


    public void getORCIdCard(String fileapth) {//该接口需要添加addHeader("Authorization", "APPCODE " + "ab3c45977cdb4b1693a58606e60fe51a")
//        String url = "https://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json";
        OrcIdUtil.getORCIdCard(fileapth, new ApiListener() {
            @Override
            public void onRequestStart(String requestUrl, int requestId) {

            }

            @Override
            public void onRequestComplete(String requestUrl, int requestId) {
                removeProgressDialog();
            }

            @Override
            public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
                tvcontent.setText("识别结果=成功=" + requestJson.toString());
            }

            @Override
            public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {
                tvcontent.setText("识别结果=失败=" + errorMsg);
            }
        });
    }
}
